﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Swift;
using TB;

namespace Server {
    public class GameServer : Port, IFrameDrived{

        public Timer Timer;
        
        /// <summary>
        /// 所有游戏集合，包括正在匹配玩家的 和 正在游戏的
        /// </summary>
        List<Game> games = new List<Game> ();
        List<Game> removedGames = new List<Game> ();

        public GameServer() {

            OnMessage ("Match", Match );

        }
        
        public void Match(Connection conn, IReadableBuffer data) {

            Console.WriteLine ("产生一个新的连接");

            int i;
            for(i = 0; i < games.Count; i++) {
                if(games[i].Num == 1) {
                    games[i].Add (conn);

                    Timer.RemoveEvent ("Match" + games[i].GetHashCode ());
                    games[i].Start ();


                    break;
                }
            }

            if(i >= games.Count) {  // 不能直接开始游戏
                Game game = new Game ();
                AddComponent ("Game" + game.GetHashCode(), game);

                game.Add (conn);
                games.Add (game);

                // 添加一个匹配超时事件，30 s
                int co = 30;
                Timer.AddEvent ("Match" + game.GetHashCode (), 0, 1000, (name) => {
                    co--;

                    if(co < 0) {  // 超时

                        IWriteableBuffer w = conn.BeginSend ("MatchHelper");
                        w.Write ("Match");
                        w.Write ("Overtime");
                        conn.End (w);

                        game.Status = 0;

                    } else {

                        IWriteableBuffer w = conn.BeginSend ("MatchHelper");
                        w.Write ("Match");
                        w.Write ("Matching");
                        w.Write (co);
                        conn.End (w);

                    }


                });
            }
        }

        public void OnTimeElapsed(int te) {

            removedGames.Clear ();

            // 判断有没有结束的游戏
            foreach(Game g in games) {
                if(g.Status == 0) {
                    g.Close ();
                    removedGames.Add (g);
                }
            }

            foreach(Game g in removedGames) {
                games.Remove (g);
            }

            // 正常游戏
            for(int i = 0; i < games.Count; i++) {
                games[i].OnTimeElapsed (te);
            }
        }
    }
}
